//
//  LSHongBaoVC.m
//  HappyStore
//
//  Created by 陈锋 on 2016/10/24.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "LSHongBaoVC.h"
#import "LSPayResultVC.h"

@interface LSHongBaoVC ()<UIGestureRecognizerDelegate,UIActionSheetDelegate,UITextFieldDelegate>{

    NSString * order_no;

}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UITextField *priceText;//金额
@property (weak, nonatomic) IBOutlet UITextField *sendText;//留言
@property (weak, nonatomic) IBOutlet UILabel *sendPriceLabel;//发送金额
@property (weak, nonatomic) IBOutlet UIButton *sendBtn;
@property (weak, nonatomic) IBOutlet UILabel *ZhiFuLabel;

@property (strong, nonatomic) NSMutableArray  *dotArray;//装小黑点
@end

@implementation LSHongBaoVC

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentView) name:@"alipayResult" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentFailedView) name:@"alipayFailed" object:nil];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
}

-(void)presentFailedView{
    
    // 跳转至支付失败页面
    LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
    [LSPayResult setCashTypeWithCashFailed];
    [self.navigationController pushViewController:LSPayResult animated:YES];
    
}

-(void)presentView{
    
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    
    if (self.sendText.text == nil || [self.sendText.text isEqualToString:@""]) {
        
        dict[@"text"] = @"恭喜发财，大吉大利！";
        
    }else{
        
        dict[@"text"] = self.sendText.text;
        
    }
    
    NSMutableDictionary * mutableParams = [NSMutableDictionary dictionary];
    mutableParams[@"userId"] = allConstMemberid;
    mutableParams[@"token"] = allConstMemberToken;
    mutableParams[@"type"] = @(1);
    mutableParams[@"redNum"] = self.tlzDict[@"peopleList"];
    mutableParams[@"redMoney"] = self.priceText.text;
    mutableParams[@"describe"] = dict[@"text"];
    mutableParams[@"payWay"] = @(2);
    mutableParams[@"groupId"] = self.tlzDict[@"discussionId"];
    
    NSString *str = @"sendRed_app_social.im.lensum?";
    
    [LSHttpTool sendHttpData:str params:mutableParams success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            dict[@"resID"] = dicInfo[@"data"];
            
            LSSimpleMessageVC * LSSimpleMessage = [[LSSimpleMessageVC alloc]init];
            
            LSSimpleMessage.content = dict[@"text"];
            
            [[RCIM sharedRCIM] sendMessage:ConversationType_DISCUSSION targetId:self.tlzDict[@"discussionId"] content:LSSimpleMessage pushContent:dict[@"text"] pushData:dict[@"text"] success:^(long messageId) {
                
                RCMessage * message = [[RCIMClient sharedRCIMClient] getMessage:messageId];
                long strId;
                NSString * strUid;
                strId = message.messageId;
                strUid = message.messageUId;
                
                NSMutableDictionary * mutableParam = [NSMutableDictionary dictionary];
                mutableParam[@"redId"] = dict[@"resID"];
                mutableParam[@"token"] = allConstMemberToken;
                mutableParam[@"messageId"] = strUid;
                
                NSString *str = @"setMessageId_app_social.im.lensum?";
                
                [LSHttpTool sendHttpData:str params:mutableParam success:^(id responseObject) {
                    
                    NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                    
                    if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                        
                        NSLog(@"**********%@***********",[dicInfo objectForKey:@"msg"]);
                        
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"sendHongBao" object:nil userInfo:dict];
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            [self dismissViewControllerAnimated:YES completion:nil];
                            
                        });
                        
                    }
                    
                    
                } failure:^(NSError *error) {

                    [self showSingleIconBubble:@"网络连接错误"];
                    
                }];
                
                
                
            } error:^(RCErrorCode nErrorCode, long messageId) {
                
            }];
            
            
        }else{

                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:[dicInfo objectForKey:@"msg"]
                                                               delegate:self
                                                      cancelButtonTitle:@"确认"
                                                      otherButtonTitles:nil];

        }
        
        
    } failure:^(NSError *error) {

       [self showSingleIconBubble:@"网络连接错误"];
        
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.priceText.keyboardType = UIKeyboardTypeDecimalPad;
    
    UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
    PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
    PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
    PrivateLetterTap.delegate= self;
    [self.scrollView addGestureRecognizer:PrivateLetterTap];
    
    self.sendBtn.layer.masksToBounds = YES;
    self.sendBtn.layer.cornerRadius = 8.0f;
    
    [self.priceText addTarget:self action:@selector(priceTextBegain:) forControlEvents:UIControlEventEditingChanged];
    
    self.ZhiFuLabel.text = @"余额";
}

- (void)tapAvatarView: (UITapGestureRecognizer *)gesture
{
    [self.priceText resignFirstResponder];
    [self.sendText resignFirstResponder];
}

//返回
- (IBAction)backBtn:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//选择支付方式
- (IBAction)changePayBtn:(UIButton *)sender {
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"支付选择"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"余额",@"支付宝", nil];
    actionSheet.tag = 100;
    [actionSheet showInView:self.view];
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (actionSheet.tag) {
        case 100://性别
        {
            
            switch (buttonIndex) {
                case 0:
                {
                    self.ZhiFuLabel.text = @"余额";
                }
                    break;
                case 1:
                {
                    self.ZhiFuLabel.text = @"支付宝";
                }
                    break;
        }
    }
            
    }
}

//发送按钮
- (IBAction)sendBtn:(UIButton *)sender {
    
     NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    
    if ([self.priceText.text floatValue] <= 0) {
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"金额不得少于0元!" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
        [alert show];
        
    }else{
        
        
        if (self.sendText.text == nil || [self.sendText.text isEqualToString:@""]) {

            dict[@"text"] = @"恭喜发财，大吉大利！";
            
        }else{
        
            dict[@"text"] = self.sendText.text;
        
        }
        
        if ([self.ZhiFuLabel.text isEqualToString:@"余额"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"余额支付" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.alertViewStyle = UIAlertViewStylePlainTextInput;
            UITextField *title = [alert textFieldAtIndex:0];
            //更改输入框
            [self inputBoxTextField:title];
            
            [alert showAlertWithCompletionHandler:^(NSInteger buttonIndex) {
                if(buttonIndex == 1){
                    UITextField *tf=[alert textFieldAtIndex:0];
                    if (tf.text.length > 0) {
                        
                        NSMutableDictionary * mutableParams = [NSMutableDictionary dictionary];
                        mutableParams[@"userId"] = allConstMemberid;
                        mutableParams[@"token"] = allConstMemberToken;
                        mutableParams[@"type"] = @(1);
                        mutableParams[@"redNum"] = self.tlzDict[@"peopleList"];
                        mutableParams[@"redMoney"] = self.priceText.text;
                        mutableParams[@"describe"] = dict[@"text"];
                        mutableParams[@"payWay"] = @(1);
                        mutableParams[@"groupId"] = self.tlzDict[@"discussionId"];
                        mutableParams[@"payPass"] = tf.text;
                        
                        NSString *str = @"sendRed_app_social.im.lensum?";
                        
                        [LSHttpTool sendHttpData:str params:mutableParams success:^(id responseObject) {
                            
                            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                            NSLog(@"结果%@",dicInfo[@"msg"]);
                            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                                
                                dict[@"resID"] = dicInfo[@"data"];
                                
                                LSSimpleMessageVC * LSSimpleMessage = [[LSSimpleMessageVC alloc]init];
                                
                                LSSimpleMessage.content = dict[@"text"];
                                
                                [[RCIM sharedRCIM] sendMessage:ConversationType_DISCUSSION targetId:self.tlzDict[@"discussionId"] content:LSSimpleMessage pushContent:dict[@"text"] pushData:dict[@"text"] success:^(long messageId) {
                                    
                                    RCMessage * message = [[RCIMClient sharedRCIMClient] getMessage:messageId];
                                    long strId;
                                    NSString * strUid;
                                    strId = message.messageId;
                                    strUid = message.messageUId;
                                    
                                    NSMutableDictionary * mutableParam = [NSMutableDictionary dictionary];
                                    mutableParam[@"redId"] = dict[@"resID"];
                                    mutableParam[@"token"] = allConstMemberToken;
                                    mutableParam[@"messageId"] = strUid;
                                    
                                    NSString *str = @"setMessageId_app_social.im.lensum?";
                                    
                                    [LSHttpTool sendHttpData:str params:mutableParam success:^(id responseObject) {
                                        
                                        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                                        
                                        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                                            
                                            NSLog(@"**********%@***********",[dicInfo objectForKey:@"msg"]);
                                            
                                            [[NSNotificationCenter defaultCenter]postNotificationName:@"sendHongBao" object:nil userInfo:dict];
                                            
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                
                                                [self dismissViewControllerAnimated:YES completion:nil];
                                                
                                            });
                                            
                                        }
                                        
                                        
                                    } failure:^(NSError *error) {

                                        [self showSingleIconBubble:@"网络连接错误"];
                                        
                                    }];
                                    
                                    
                                    
                                } error:^(RCErrorCode nErrorCode, long messageId) {
                                    
                                }];
                                
                                
                            }else{
                                
                                if ([[dicInfo objectForKey:@"msg"] isEqualToString:@"支付密码错误"]) {
                                    
                                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付失败"
                                                                                    message:[dicInfo objectForKey:@"msg"]
                                                                                   delegate:self
                                                                          cancelButtonTitle:@"取消"
                                                                          otherButtonTitles:@"立即设置",nil];
                                    alert.tag = 20;
                                    [alert show];
                                    
                                }else if([[dicInfo objectForKey:@"msg"] isEqualToString:@"余额不足"]){
                                    
                                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付失败"
                                                                                    message:[dicInfo objectForKey:@"msg"]
                                                                                   delegate:self
                                                                          cancelButtonTitle:@"取消"
                                                                          otherButtonTitles:@"立即充值",nil];
                                    alert.tag = 10;
                                    [alert show];
                                    
                                }
                                
                            }
                            
                            
                        } failure:^(NSError *error) {

                            [self showSingleIconBubble:@"网络连接错误"];
                            
                        }];
                        
                    }else{
                        
                        NSString *strMsg = @"密码不能为空";
                        
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:strMsg delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
                        [alert show];
                        
                    }
                }
            }];

        }else if ([self.ZhiFuLabel.text isEqualToString:@"支付宝"]){
        
        order_no = [LSAlipay alipay:@"乐商网红包" body:@"红包" price:[self.priceText.text doubleValue]];
        
        }
        
        
    
    }
    
}

-(void)priceTextBegain:(UITextField *)textFile{
    self.priceText = textFile;
    self.sendPriceLabel.text = [NSString stringWithFormat:@"¥%@",self.priceText.text];

}

#pragma mark - alertview

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 1) {
        
        switch (alertView.tag) {
            case 10:
            {
                [self dismissViewControllerAnimated:YES completion:nil];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"RechargePrice" object:nil];
                
                break;
            }
            case 20:
                
            {
                [self dismissViewControllerAnimated:YES completion:nil];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"setPayPass" object:nil];
                
                break;
            }
                
            default:
                break;
        }
    }
    
    
}
#pragma mark - 支付输入框
- (void)inputBoxTextField:(UITextField *)textField{
    //            [title setSecureTextEntry:YES];
    textField.borderStyle = UITextBorderStyleNone;
    textField.textColor = [UIColor clearColor];
    textField.delegate = self;
    textField.font = [UIFont systemFontOfSize:16.0f];
    //            title.placeholder = @"请输入支付密码";
    //光标颜色
    textField.tintColor = [UIColor clearColor];
    textField.keyboardType = UIKeyboardTypeNumberPad;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    //每个密码输入框的宽度
    CGFloat lwidth = 38;
    CGFloat kDotCount = 6;
    CGSize kDotSize = CGSizeMake(10, 10);//小黑点
    for (int i = 0; i < 5; i++) {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake((i + 1) * lwidth, 0, 0.5, 20)];
        lineView.backgroundColor = RGB(230, 230, 230);
        [textField addSubview:lineView];
    }
    self.dotArray = [NSMutableArray array];
    //生成中间的点
    for (int i = 0; i < kDotCount; i++) {
        UIView *dotView = [[UIView alloc] initWithFrame:CGRectMake(0 + (lwidth - kDotCount) / 2 + i * lwidth, 0 + (20 - kDotSize.height) / 2, kDotSize.width, kDotSize.height)];
        dotView.backgroundColor = RGB(45, 45, 45);
        dotView.layer.cornerRadius = kDotSize.width / 2.0f;
        dotView.clipsToBounds = YES;
        dotView.hidden = YES; //先隐藏
        [textField addSubview:dotView];
        //把创建的黑色点加入到数组中
        [self.dotArray addObject:dotView];
    }
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //    NSLog(@"变化%@", string);
    if ([string isEqualToString:@"\n"]) {
        //按回车关闭键盘
        [textField resignFirstResponder];
        return NO;
    }else if(string.length == 0) {
        //判断是不是删除键
        return YES;
    }else if (textField.text.length >=6){
        //输入的字符个数大于6，则无法继续输入，返回NO表示禁止输入
        //        NSLog(@"输入的字符个数大于6，忽略输入");
        return NO;
    }else{
        return YES;
    }
}
/**
 * 重置显示的点
 */
- (void)textFieldDidChange:(UITextField *)textField{
//    NSLog(@"%@", textField.text);
    for (UIView *dotView in self.dotArray) {
        dotView.hidden = YES;
    }
    for (int i = 0; i < textField.text.length; i++) {
        ((UIView *)[self.dotArray objectAtIndex:i]).hidden = NO;
    }
    if (textField.text.length == 6) {
//        NSLog(@"输入完毕");
    }
}

@end
